﻿using System.Collections.Specialized;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace IntraVision.Web
{
    public static class URLHelper
    {
        public const string DefaultControllerName = "DefaultController";
        public const string DefaultAction = "Default";

        public static string GetBaseHref(HttpContext context)
        {
            StringBuilder href = new StringBuilder();
            href.Append("http://").Append(context.Request.Url.Host);
            if (context.Request.Url.Port != 80) href.Append(':').Append(context.Request.Url.Port.ToString());
            href.Append(context.Request.ApplicationPath);
            string result = href.ToString();
            if (!result.EndsWith("/")) result += "/";
            return result;
        }
        /// <summary>
        /// Gets URL like ~/Users/View/12 and returns array of strings, splitted by "/".
        /// </summary>
        /// <param name="url">URL in ~/Users/View/12 format</param>
        /// <returns>string[]</returns>
        public static string[] GetURLParts(string url)
        {
            //Remove ~/
            if (url.StartsWith("~/")) url = url.Remove(0, 2);
            //Trim slashes from the beginning and the end of the url
            char[] trimChars = new char[] { '/', '\\' };
            url = url.TrimStart(trimChars).TrimEnd(trimChars);

            //Split url by '/'
            string[] sourceUrlParts = url.Split('/');
            
            //Create array with minimum length of 2 (0-controller,1-action)
            string[] targetUrlParts = new string[(sourceUrlParts.Length < 2) ? 2 : sourceUrlParts.Length];
            
            //Set default controller and action
            targetUrlParts[0] = DefaultControllerName;
            targetUrlParts[1] = DefaultAction;
            
            //Copy params from source URL if defined
            if (!string.IsNullOrEmpty(url))
            {
                for (int i = 0; i < sourceUrlParts.Length; i++)
                    targetUrlParts[i] = sourceUrlParts[i];
            }

            return targetUrlParts;
        }

        /// <summary>
        /// Gets redirect url by original url and collection of urls, that should be rewrited.
        /// </summary>
        /// <param name="originalURL">Original url</param>
        /// <param name="appPath">Application path. All "~" symbols in url collection will be replaced with this path.</param>
        /// <param name="urls">Pairs of regex-allowed keys and regex-allowed values</param>
        /// <returns>Redirect url, or null if no redirect url was found.</returns>
        public static string GetRedirectUrl(string originalURL, string appPath, NameValueCollection urls)
        {
            if (urls == null) return null;
            originalURL = originalURL.Replace("~", appPath);

            foreach (string pattern in urls.Keys)
            {
                Regex re = new Regex(pattern.Replace("~", appPath), RegexOptions.IgnoreCase);
                if (re.IsMatch(originalURL))
                    return re.Replace(originalURL, urls[pattern]);
            }
            return null;
        }

        /// <summary>
        /// Gets redirect url by original url and collection of urls, that should be rewritten. If collection is not specified, web.config section named "urlRewrite" is used.
        /// </summary>
        /// <param name="originalURL">Original url</param>
        /// <returns>Redirect url, or null if no redirect url was found.</returns>
        public static string GetRedirectUrl(string originalURL, string appPath)
        {
            return GetRedirectUrl(originalURL, appPath, ConfigurationManager.GetSection("urlRewrite") as NameValueCollection);
        }
    }
}
